package socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 模拟客户端.
 *
 * @author 宫新程
 * @since 2018/12/23 8:25 PM
 */
public class MyClient {

  private static final Logger logger = LoggerFactory.getLogger(MyServer.class);

  /** 模拟客户端. */
  public static void main(String[] args) throws IOException {
    ExecutorService pool = Executors.newFixedThreadPool(4);


    // 多线程发送请求
    for (int i = 0; i < 4; i++) {
      // 与客户端创建连接.
      Socket client = new Socket("127.0.0.1", 8888);

      pool.execute(
          () -> {
            try {
              // 创建输出流.
              OutputStream outputStream = client.getOutputStream();
              PrintWriter out = new PrintWriter(outputStream);
              out.print("Hello World ！");
              out.flush();
              /** 必须加这一句话，否则服务端会一直等待输入流. */
              client.shutdownOutput();

              // 从输入流中获取数据.
              // 获取输入流，得到客户端返回的数据
              InputStream inputStream = client.getInputStream();
              BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
              String result = br.lines().collect(Collectors.joining(System.lineSeparator()));
              System.out.println("客户端接收到的数据为：" + result);

              // 关闭连接
              inputStream.close();
              outputStream.close();
              client.close();
            } catch (Exception e) {
              e.printStackTrace();
            }
          });
    }

    pool.shutdown();
  }
}
